package com.shjy.client.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.shjy.client.R;
import com.shjy.client.alipay.AlipayConfig;
import com.shjy.client.alipay.OrderInfoUtil2_0;
import com.shjy.client.delegate.DetailWebviewDelegate;
import com.shjy.client.util.Const;
import com.shjy.client.wxapi.WXConfig;
import com.shjy.client.wxapi.WXPayUtil;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class DetailActivity extends AppCompatActivity {

    private Toolbar mToolbar;
    private TextView mToolbarTitleTextView;
    private TextView mBackTextView;
    private ImageView mImageView;
    private Button mButton;

    private ProgressBar mProgressBar;
    private WebView mWebView;

    private View mBottomNavigationBarView;
    private TextView menuHome;
    private TextView menuOrder;
    private TextView menuMe;

    private Handler mHandler;

    private int mCurrentMenu;

    private String out_trade_no;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // layout
        setContentView(R.layout.activity_detail);

        // 初始化 Handler
        initHandler();

        // 初始化 Toolbar
        initToolbar();

        // 初始化 网页加载进度条
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);

        // 初始化 Webview
        initWebview();

        // 初始化 底部导航栏
        initBottomNavigationBar();
    }

    @Override
    protected void onRestart() {
        super.onRestart();

        mWebView.reload();
    }

    @Override
    protected void onResume() {
        super.onResume();

        int defValue = 20171231;

        // 微信支付结果
        SharedPreferences sharedPreferences = getSharedPreferences("pay", Context.MODE_PRIVATE);
        int errCode = sharedPreferences.getInt("WXPay_errCode", defValue);

        if (errCode != defValue) {

            // 移除支付结果
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.remove("WXPay_errCode");
            editor.commit();

            // -2:取消支付
            if (errCode == -2) {

                return;
            }

            String result = "";
            String message = "";

            // 支付成功 0:成功 -1:失败 -2:取消
            if (errCode == 0) {

                result = "1"; // 支付成功
            } else if (errCode == -1) {

                message = "微信支付失败！";
            }

            mWebView.loadUrl("javascript:window.finishPhonePay('" + out_trade_no + "', '" + result + "', '" + message + "')");
        }
    }

    @Override
    public void onBackPressed() {

        String url = mWebView.getUrl();
        boolean canGoBack = mWebView.canGoBack() && !(url.indexOf("select_track.html") != -1 || url.indexOf("order_list.html") != -1);

        if (canGoBack) {
            if (url.indexOf("order_detail.html") != -1 ||
                    url.indexOf("order_trace.html") != -1 ||
                    url.indexOf("price_detail.html") != -1) {
                // 从首页跳转过来的
                if (getIntent().getIntExtra("currentMenu", 3) == 0) {
                    // 跳转到订单列表页
                    mWebView.loadUrl(Const.URL_ORDERLIST);
                } else if (getIntent().getIntExtra("currentMenu", 3) == 1) { // 从订单跳转过来的
                    // 跳转到订单列表页
                    super.onBackPressed();
                }
            } else if (url.indexOf("order_ok.html") != -1) {
                // 跳转到订单详细页
                url = url.replace("order_ok.html", "order_detail.html");
                mWebView.loadUrl(url);
            } else if ((url.indexOf("input_order.html") != -1) || (url.indexOf("input_order_now.html") != -1)) {

                if ((url.indexOf("input_order.html") != -1)) {
                    // 跳转到选车页
                    url = url.replace("input_order.html", "select_track.html?callType=BOOK&fromType=INDEX");
                } else {
                    // 跳转到选车页
                    url = url.replace("input_order_now.html", "select_track.html?callType=NOW&fromType=INDEX");
                }
                mWebView.loadUrl(url);
            } else {
                mWebView.goBack();
            }
        } else {
            if (url.indexOf("order_ok.html") != -1) {
                // 跳转到订单详细页
                url = url.replace("order_ok.html", "order_detail.html");
                mWebView.loadUrl(url);
            } else {
                super.onBackPressed();
            }
        }
    }

    private void initHandler() {
        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what == Const.DETAIL_WHAT_PAY) {

                    Map<String, String> map = (Map<String, String>) msg.obj;
                    String payType = map.get("payType");

                    // 支付宝支付
                    if (Const.PAY_TYPE_ZFB.equals(payType)) {

                        Map<String, String> payMap = new HashMap();
                        payMap.put("total_amount", map.get("total_amount"));
                        payMap.put("subject", map.get("out_trade_no"));
                        payMap.put("out_trade_no", map.get("out_trade_no"));

                        out_trade_no = map.get("out_trade_no");

                        alipay(payMap);
                    } else if (Const.PAY_TYPE_WX.equals(payType)) {

                        Map<String, String> payMap = new HashMap<String, String>();
                        payMap.put("nonce_str", map.get("nonce_str"));
                        payMap.put("sign", map.get("sign"));
                        payMap.put("prepayid", map.get("prepayid"));

                        out_trade_no = map.get("prepayid");

                        wxpay(payMap);
                    }
                } else if (msg.what == Const.DETAIL_WHAT_PAY_RESULT) {

                    Map<String, String> map = (Map<String, String>) msg.obj;
                    mWebView.loadUrl("javascript:window.finishPhonePay('" + out_trade_no + "', '" + map.get("result") + "', '" + map.get("message") + "')");
                }
            }
        };
    }

    private void initToolbar() {

        // 导航栏标题
        setTitle("");

        // 导航栏设定
        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        // 导航栏标题
        mToolbarTitleTextView = (TextView) mToolbar.findViewById(R.id.titleTextView);
        mToolbarTitleTextView.setText("");

        // 设定导航栏返回图标的大小
        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);

        float density = outMetrics.density;
        int right = (int) (20 * density);
        int bottom = right;
        Rect bounds = new Rect(0, 0, right, bottom);

        // 导航栏返回
        mBackTextView = (TextView) mToolbar.findViewById(R.id.backTextView);
        Drawable[] drawables = mBackTextView.getCompoundDrawables();
        Drawable drawable = drawables[0];
        drawable.setBounds(bounds);
        mBackTextView.setCompoundDrawables(drawable, null, null, null);
        mBackTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        // logo
        mImageView = (ImageView) mToolbar.findViewById(R.id.logoImageView);
        mImageView.setVisibility(View.VISIBLE);

        // 提交按钮
        mButton = (Button) mToolbar.findViewById(R.id.button);
        mButton.setVisibility(View.INVISIBLE);
        mButton.setEnabled(false);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebView.loadUrl("javascript:save()");
            }
        });

        setSupportActionBar(mToolbar);
    }

    private void initWebview() {

        // webview
        mWebView = (WebView) findViewById(R.id.webview);

        // 优先使用缓存
        //mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        mWebView.getSettings().setDomStorageEnabled(true);

        mWebView.setWebChromeClient(new DetailWebChromeClient());
        mWebView.setWebViewClient(new DetailWebViewClient());
        mWebView.addJavascriptInterface(new DetailWebviewDelegate(this, mHandler, mWebView), "delegate");

        mWebView.loadUrl(getIntent().getStringExtra("url"));
    }

    private void initBottomNavigationBar() {

        mBottomNavigationBarView = findViewById(R.id.bottomNavigationBar);

        menuHome = (TextView) findViewById(R.id.menu_home);
        menuOrder = (TextView) findViewById(R.id.menu_order);
        menuMe = (TextView) findViewById(R.id.menu_me);

        resetBottomNavigationBar();

        // 首页
        menuHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 返回结果
                Intent intent = new Intent();
                intent.putExtra("menuIndex", "0");
                setResult(MainActivity.WHAT_TO_DETAIL, intent);
                finish();

                // 重新设定底部导航栏
                resetBottomNavigationBar();
                menuHome.setTextColor(getResources().getColor(R.color.colorBottomMenuSelected));
                Drawable[] drawables = menuHome.getCompoundDrawables();
                Drawable drawable = getResources().getDrawable(R.drawable.i_home_selected);
                drawable.setBounds(drawables[1].getBounds());
                menuHome.setCompoundDrawables(null, drawable, null, null);

                mCurrentMenu = 0;
            }
        });
        // 订单
        menuOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 重新设定底部导航栏
                resetBottomNavigationBar();
                menuOrder.setTextColor(getResources().getColor(R.color.colorBottomMenuSelected));
                Drawable[] drawables = menuOrder.getCompoundDrawables();
                Drawable drawable = getResources().getDrawable(R.drawable.i_order_selected);
                drawable.setBounds(drawables[1].getBounds());
                menuOrder.setCompoundDrawables(null, drawable, null, null);

                mCurrentMenu = 1;
            }
        });

        // 我的
        menuMe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mWebView.loadUrl(Const.URL_ME);

                // 重新设定底部导航栏
                resetBottomNavigationBar();
                menuMe.setTextColor(getResources().getColor(R.color.colorBottomMenuSelected));
                Drawable[] drawables = menuMe.getCompoundDrawables();
                Drawable drawable = getResources().getDrawable(R.drawable.i_me_selected);
                drawable.setBounds(drawables[1].getBounds());
                menuMe.setCompoundDrawables(null, drawable, null, null);

                mCurrentMenu = 2;
            }
        });

        menuOrder.setTextColor(getResources().getColor(R.color.colorBottomMenuSelected));
        Drawable[] drawables = menuOrder.getCompoundDrawables();
        Drawable drawable = getResources().getDrawable(R.drawable.i_order_selected);
        drawable.setBounds(drawables[1].getBounds());
        menuOrder.setCompoundDrawables(null, drawable, null, null);

        mCurrentMenu = 1;
    }

    private void resetBottomNavigationBar() {

        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        float density = outMetrics.density;
        int right = (int) (25 * density);
        int bottom = right;

        int colorNormal = getResources().getColor(R.color.colorBottomMenuNormal);
        Rect bounds = new Rect(0, 0, right, bottom);

        menuHome.setTextColor(colorNormal);
        Drawable[] drawables = menuHome.getCompoundDrawables();
        Drawable drawable = getResources().getDrawable(R.drawable.i_home);
        drawable.setBounds(bounds);
        menuHome.setCompoundDrawables(null, drawable, null, null);

        menuOrder.setTextColor(colorNormal);
        drawables = menuHome.getCompoundDrawables();
        drawable = getResources().getDrawable(R.drawable.i_order);
        drawable.setBounds(bounds);
        menuOrder.setCompoundDrawables(null, drawable, null, null);

        menuMe.setTextColor(colorNormal);
        drawables = menuHome.getCompoundDrawables();
        drawable = getResources().getDrawable(R.drawable.i_me);
        drawable.setBounds(bounds);
        menuMe.setCompoundDrawables(null, drawable, null, null);

        mCurrentMenu = 0;
    }

    // 支付宝支付
    private void alipay(Map<String, String> map) {

        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(AlipayConfig.APPID, map);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = AlipayConfig.RSA2_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, true);
        final String orderInfo = orderParam + "&" + sign;

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(DetailActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.d("alipay", result.toString());

                Map<String, String> obj = new HashMap<String, String>();
                String resultStatus = result.get("resultStatus");
                String memo = result.get("memo");

                if (TextUtils.isEmpty(memo)) {
                    if (TextUtils.equals(resultStatus, "9000")) {
                        memo = "订单支付成功";
                    } else if (TextUtils.equals(resultStatus, "8000")) {
                        memo = "正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态";
                    } else if (TextUtils.equals(resultStatus, "4000")) {
                        memo = "订单支付失败";
                    } else if (TextUtils.equals(resultStatus, "5000")) {
                        memo = "重复请求";
                    } else if (TextUtils.equals(resultStatus, "6001")) {
                        memo = "用户中途取消";
                    } else if (TextUtils.equals(resultStatus, "6002")) {
                        memo = "网络连接出错";
                    } else if (TextUtils.equals(resultStatus, "6004")) {
                        memo = "支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态";
                    } else {
                        memo = "其它支付错误";
                    }
                }
                if (TextUtils.equals(resultStatus, "9000")) {
                    obj.put("result", "1");
                } else {
                    obj.put("result", resultStatus);
                }
                obj.put("message", memo);

                Message msg = new Message();
                msg.what = Const.DETAIL_WHAT_PAY_RESULT;
                msg.obj = obj;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 微信支付
     * @param map 参数Map
     */
    private void wxpay(Map<String, String> map) {

        // 应用ID
        String appid = WXConfig.APP_ID;
        // 商户号
        String partnerid = WXConfig.PARTNER_ID;
        // 预支付交易会话ID
        String prepayid = map.get("prepayid");
        // 扩展字段
        String packageValue = "Sign=WXPay";
        // 随机字符串
        String noncestr = WXPayUtil.generateRandomString();
        // 时间戳
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        // 签名
        String sign = "";

        // 生成签名参数Map
        SortedMap<String, String> parameters = new TreeMap<String, String>();

        // 应用ID
        parameters.put("appid", appid);
        // 商户号
        parameters.put("partnerid", partnerid);
        // 预支付交易会话ID
        parameters.put("prepayid", prepayid);
        // 扩展字段
        parameters.put("package", packageValue);
        // 随机字符串
        parameters.put("noncestr", noncestr);
        // 时间戳
        parameters.put("timestamp", timestamp);

        // 生成签名
        sign = WXPayUtil.generateSign(parameters);

        // 微信API
        IWXAPI wxapi = WXAPIFactory.createWXAPI(this, WXConfig.APP_ID);
        // 注册应用
        wxapi.registerApp(WXConfig.APP_ID);

        // 支付请求
        PayReq req = new PayReq();
        // 应用ID
        req.appId = appid;
        // 商户号
        req.partnerId = partnerid;
        // 预支付交易会话ID
        req.prepayId = prepayid;
        // 扩展字段
        req.packageValue = packageValue;
        // 随机字符串
        req.nonceStr = noncestr;
        // 时间戳
        req.timeStamp = timestamp;
        // 签名
        req.sign = sign;

        // 发起支付请求
        wxapi.sendReq(req);
    }

    class DetailWebChromeClient extends WebChromeClient {

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
            builder.setTitle(null).setMessage(message).setPositiveButton("确定", null);
            builder.setCancelable(false);
            AlertDialog dialog = builder.create();
            dialog.show();
            result.confirm();
            return true;
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            mToolbarTitleTextView.setText(title);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            mProgressBar.setProgress(newProgress);
            if (mProgressBar.getProgress() == mProgressBar.getMax()) {
                mProgressBar.setVisibility(View.GONE);
            }
            super.onProgressChanged(view, newProgress);
        }
    }

    class DetailWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {

            if (url.indexOf("login.html") != -1) {

                // 跳转到LoginActivity
                Intent intent = new Intent(DetailActivity.this, LoginActivity.class);
                startActivity(intent);
                // 停止加载
                mWebView.stopLoading();
            } else if (url.indexOf("index.html") != -1) {

                // 等待接单页面点击取消，返回到首页
                menuHome.performClick();

                // 停止加载
                mWebView.stopLoading();
            } else {

                // 导航栏 显示logo，隐藏提交按钮
                mImageView.setVisibility(View.VISIBLE);
                mButton.setVisibility(View.INVISIBLE);
                mButton.setEnabled(false);
                // 选择 出发地址／结束地址
                if ((url.indexOf("select_address.html") != -1) || (url.indexOf("order_ok.html") != -1)) {
                    // 导航栏 隐藏logo，显示提交按钮
                    mImageView.setVisibility(View.INVISIBLE);
                    mButton.setVisibility(View.VISIBLE);
                    mButton.setEnabled(true);
                }

                mBottomNavigationBarView.setVisibility(View.GONE);
                // 订单详情页，订单轨迹页，订单价格页 显示底部菜单
                if (url.indexOf("order_detail.html") != -1 || url.indexOf("order_trace.html") != -1 || url.indexOf("price_detail.html") != -1) {
                    mBottomNavigationBarView.setVisibility(View.VISIBLE);
                }

                mBackTextView.setVisibility(View.VISIBLE);
                if (url.indexOf("wait_order.html") != -1) {
                    // 导航栏 隐藏返回按钮
                    mBackTextView.setVisibility(View.INVISIBLE);
                }

                // 显示进度条
                mProgressBar.setVisibility(View.VISIBLE);
                mProgressBar.setProgress(0);
            }
        }
    }
}
